package com.channel.modules.system.service.Impl;

import cn.hutool.core.collection.CollectionUtil;
import com.channel.modules.system.domain.Dict;
import com.channel.modules.system.repository.DictRepository;
import com.channel.modules.system.service.DictService;
import com.channel.modules.system.service.dto.DictDetailDto;
import com.channel.modules.system.service.dto.DictDto;
import com.channel.modules.system.service.dto.DictQueryCriteria;
import com.channel.modules.system.service.mapstruct.DictMapper;
import com.commons.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Service
@CacheConfig(cacheNames = "dict")
public class DictServiceImpl implements DictService {

    private final DictRepository dictRepository;
    private final DictMapper dictMapper;
    private final RedisUtils redisUtils;

    @Autowired
    public DictServiceImpl(DictRepository dictRepository, DictMapper dictMapper, RedisUtils redisUtils) {
        this.dictRepository = dictRepository;
        this.dictMapper = dictMapper;
        this.redisUtils = redisUtils;
    }

    @Override
    public PageResult<DictDto> queryAll(DictQueryCriteria dict, Pageable pageable) {
        Page<Dict> page = dictRepository.findAll((root, query, cb) -> QueryHelp.getPredicate(root, dict, cb), pageable);
        return PageUtil.toPage(page.map(dictMapper::toDto));
    }

    @Override
    public List<DictDto> queryAll(DictQueryCriteria dict) {
        List<Dict> list = dictRepository.findAll((root, query, cb) -> QueryHelp.getPredicate(root, dict, cb));
        return dictMapper.toDto(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Dict resources) {
        dictRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Dict resources) {
        //清理缓存
        delCaches(resources);
        dictRepository.findById(resources.getId()).orElseGet(Dict::new);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<Long> ids) {
        //清理缓存
        List<Dict> dicts=dictRepository.findByIdIn(ids);
        for(Dict dict:dicts){
            delCaches(dict);
        }
        dictRepository.deleteByIdIn(ids);
    }

    @Override
    public void download(List<DictDto> dictDtos, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list=new ArrayList<>();
        for(DictDto dictDto:dictDtos){
            if(CollectionUtil.isNotEmpty(dictDto.getDictDetails())){
                for(DictDetailDto dictDetailDto:dictDto.getDictDetails()){
                    Map<String,Object> map=new LinkedHashMap<>();
                    map.put("字典名称", dictDto.getName());
                    map.put("字典描述", dictDto.getDescription());
                    map.put("字典标签", dictDetailDto.getLabel());
                    map.put("字典值", dictDetailDto.getValue());
                    map.put("创建日期", dictDetailDto.getCreateTime());
                    list.add(map);
                }
            }else {
                Map<String,Object> map = new LinkedHashMap<>();
                map.put("字典名称", dictDto.getName());
                map.put("字典描述", dictDto.getDescription());
                map.put("字典标签", null);
                map.put("字典值", null);
                map.put("创建日期", dictDto.getCreateTime());
                list.add(map);
            }
        }
        FileUtil.downloadExcel(list, response);
    }

    public void delCaches(Dict dict)
    {
        redisUtils.del(CacheKey.DICT_NAME+dict.getName());
    }
}
